<template>
  <t-card :bordered="false">

    <!-- 自定义表格 -->
    <custom-table 
      ref="customTableRef" 
      row-key="id" 
      :columns="columns" 
      :api="homeEngineeringData"
      :foot-data="footData"
      :on-before-set-data="handleTableSetData"
      :rowspan-and-colspan="rowspanAndColspan" 
      max-height="calc(100vh - 280px)"
      fixed-page-size
      >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl); display: flex;">
          <t-radio-group v-model="defaultCompany" theme="button"  @change="handleInitTable" style="margin-right: 10px;">
            <t-radio-button :value="_.id" v-for="_ in companyList">{{ _.name }}</t-radio-button>
          </t-radio-group>
          <t-radio-group v-model="defaultCustomers"   @change="handleTimeChange">
            <t-radio-button v-for="_ in timeDate" :key="'report'+_.value" :value="_.value"> {{ _.name }}</t-radio-button>
          </t-radio-group>
           <t-date-range-picker enable-time-picker v-model="timeRange" allow-input clearable @change="onChange" style="margin-left: 10px;"/>
        </div>
      </template>
      <template #engineeringManagerId="{ row }">
        {{ userStore.getUserNameById(row.engineeringManagerId) }}
      </template>
      <template #supervisionId="{ row }">
        {{ userStore.getUserNameById(row.supervisionId) }}
      </template>
      <template #shiGongHeTong="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.shiGongHeTong)">{{ row.shiGongHeTong&&row.shiGongHeTong.split(',').length }}</t-link>
      </template>
      <template #daikaigong="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.daikaigong)">{{ row.daikaigong&&row.daikaigong.split(',').length }}</t-link>
      </template>
      <template #chaiQiang="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.chaiQiang)">{{ row.chaiQiang&&row.chaiQiang.split(',').length }}</t-link>
      </template>
      <template #qiQiang="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.qiQiang)">{{ row.qiQiang&&row.qiQiang.split(',').length }}</t-link>
      </template>
      <template #shuiDian="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.shuiDian)">{{ row.shuiDian&&row.shuiDian.split(',').length }}</t-link>
      </template>
      <template #waGong="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.waGong)">{{ row.waGong&&row.waGong.split(',').length }}</t-link>
      </template>
      <template #muGong="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.muGong)">{{ row.muGong&&row.muGong.split(',').length }}</t-link>
      </template>
      <template #youGong="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.youGong)">{{ row.youGong&&row.youGong.split(',').length }}</t-link>
      </template>
      <template #jungong="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.jungong)">{{ row.jungong&&row.jungong.split(',').length }}</t-link>
      </template>
      <template #shigongzhong="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.shigongzhong)">{{ row.shigongzhong&&row.shigongzhong.split(',').length }}</t-link>
      </template>
      <template #tinggong="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.tinggong)">{{ row.tinggong&&row.tinggong.split(',').length }}</t-link>
      </template>
      <template #anZhuang="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.anZhuang)">{{ row.anZhuang&&row.anZhuang.split(',').length }}</t-link>
      </template>
      <template #wanGong="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.wanGong)">{{ row.wanGong&&row.wanGong.split(',').length }}</t-link>
      </template>
      <template #tuidan="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.tuidan)">{{ row.tuidan&&row.tuidan.split(',').length }}</t-link>
      </template>

      
      

    </custom-table>

  </t-card>
</template>

<script lang="ts">
export default {
  name: 'ReportEngineering',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { computed, onMounted, onUpdated, Ref, ref, useTemplateRef } from 'vue';

import { homeEngineeringData } from '@/api/dashboard/base';
import { getCompanyList, getSimpleDeptList } from '@/api/system/dept';
import { propertyManageCRUD } from '@/api/config/property';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';

import { useDictionaryStore, useUserStore } from '@/store';
import { getUserListByRoleCode } from '@/api/system/user';
import listToTree from '@/utils/listToTree';
import disposableParams from '@/utils/disposableParams';
import { useRouter } from 'vue-router';
// 路由器
const router = useRouter();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();
// 公司列表
const companyList = ref([]);
// 默认公司
const defaultCompany = ref()
// 处理获取公司列表
const handleGetCompanyList = () => {
  getCompanyList()
    .then((data) => {
      companyList.value = data;
      defaultCompany.value = data[0].id
      handleInitTable()
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
const timeDate = [
  {value:1,name:'本周'},
  {value:2,name:'本月'},
  {value:3,name:'本年'},
  {value:4,name:'全部'},
  ]
// 时间默认
const defaultCustomers = ref(4)

const table = ref([])
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  table.value = data
  return data;
};

const hanldeGoToDesignList = (orderIds:string) => {
  if(!orderIds) return
  disposableParams.set('to-do-tree-jump-params', {
  
    orderIds: orderIds,
   
  });
  router.push({ path:'/project/engineering', query: { timeStamp: new Date().getTime() } });
}
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  {colKey:'id',title:'工程部',thClassName:'fw-b',children:[
    { colKey: 'engineeringManagerId', title: '工程部经理', align:'center' },
    { colKey: 'supervisionId', title: '监理', align:'center' },
    { colKey: 'shiGongHeTong', title: '施工合同', align:'center' },
    { colKey: 'chaiQiang', title: '拆墙' , align:'center'},
    { colKey: 'qiQiang', title: '砌墙', align:'center'},
    { colKey: 'shuiDian', title: '水电', align:'center'},
    { colKey: 'waGong', title: '瓦工', align:'center'},
    { colKey: 'muGong', title: '木工', align:'center'},
    { colKey: 'youGong', title: '油工', align:'center'},
    { colKey: 'anZhuang', title: '安装', align:'center'},
    { colKey: 'wanGong', title: '完工', align:'center'},
    { colKey: 'daikaigong', title: '待开工', align:'center'},
    { colKey: 'shigongzhong', title: '施工中', align:'center'},
    { colKey: 'jungong', title: '竣工', align:'center'},
    { colKey: 'tinggong', title: '停工', align:'center'},
    { colKey: 'tuidan', title: '退单', align:'center'},
  ]}
  
];
const rowspanAndColspan = ({ row ,col, rowIndex, colIndex }) => {
 // 合并人员名称列
 if (col.colKey === 'engineeringManagerId') {
    // 如果是当前人员的第一行数据
    if (rowIndex === 0 || table.value[rowIndex].engineeringManagerId !== table.value[rowIndex - 1].engineeringManagerId) {
      // 计算当前人员有多少行数据
      let rowspan = 1;
      for (let i = rowIndex + 1; i < table.value.length; i++) {
        if (table.value[i].engineeringManagerId === row.engineeringManagerId) {
          rowspan++;
        } else {
          break;
        }
      }
      return { rowspan, colspan: 1 };
    } else {
      return { rowspan: 0, colspan: 0 };
    }
  }
  
};
// 处理初始化表格
const handleInitTable = () => {
  // 待办树跳转参数
  const toDoTreeJumpParams = disposableParams.get('to-do-tree-jump-params');
  const params = {
    beginTime:'',
    endTime:'',
    companyId:defaultCompany.value
  }
  const now = new Date();
  
  switch(defaultCustomers.value) {
    case 1: // 本周
      const firstDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1)));
      const lastDayOfWeek = new Date(firstDayOfWeek);
      lastDayOfWeek.setDate(firstDayOfWeek.getDate() + 6);
      
      params.beginTime = dayjs(firstDayOfWeek).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfWeek).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 2: // 本月
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      
      params.beginTime = dayjs(firstDayOfMonth).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfMonth).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 3: // 本年
      const firstDayOfYear = new Date(now.getFullYear(), 0, 1);
      const lastDayOfYear = new Date(now.getFullYear(), 11, 31);
      
      params.beginTime = dayjs(firstDayOfYear).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfYear).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 4: // 全部
      // 不传日期参数
      params.beginTime='';
      params.endTime='';
      break;
  }
  if(timeRange.value.length>0) {
    params.beginTime=timeRange.value[0];
    params.endTime=timeRange.value[1];
  }
  customTableRef.value.initTable(params);
};
const handleTimeChange = () => {
  timeRange.value = []
  handleInitTable()
}
// 日期选择
const timeRange = ref([])
const onChange = (value, context) => {
  const params = {
    beginTime:'',
    endTime:'',
    companyId:defaultCompany.value
  }
  if(value.length>0) {
    params.beginTime=value[0];
    params.endTime=value[1];
    defaultCustomers.value = 0
  } else {
    params.beginTime='';
    params.endTime='';
    defaultCustomers.value = 4
  }
  customTableRef.value.initTable(params);
}
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleGetCompanyList();
});
// onUpdated(() => {
//   handleRefreshTable();
// })
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 计算汇总值
const calculateSummary = (colKey: string) => {
  if (!table.value.length) return 0;
  
  // 处理计数字段（如新增数、有效数等）
  if (['shiGongHeTong','daikaigong', 'chaiQiang', 'qiQiang','shuiDian','waGong', 'muGong', 'youGong', 'jungong', 'anZhuang', 'wanGong', 'shigongzhong', 'tinggong', 'tuidan'].includes(colKey)) {
    return table.value.reduce((sum, row) => sum + (row[colKey] ? row[colKey].split(',').length : 0), 0);
  }
  
  // 处理百分比字段（如有效率、转设计率等）
  if (colKey.endsWith('Percent')) {
    const baseField = colKey.replace('Percent', '');
    const countField = 'addCount';
    const total = table.value.reduce((sum, row) => sum + (row[countField] ? row[countField].split(',').length : 0), 0);
    const part = table.value.reduce((sum, row) => sum + (row[baseField] ? row[baseField].split(',').length : 0), 0);
    return total > 0 ? (part / total * 100).toFixed(2) + '%' : '0%';
  }
  
  // 处理金额字段
  if (colKey === 'contractPrice') {
    return table.value.reduce((sum, row) => sum + (parseFloat(row[colKey]) || 0), 0).toFixed(2);
  }
  
  return 0;
};
// 普通表尾数据
const footData = computed(() => {
  return [
    {
      engineeringManagerId: '汇总',
      shiGongHeTong: calculateSummary('shiGongHeTong'),
      chaiQiang: calculateSummary('chaiQiang'),
      qiQiang: calculateSummary('qiQiang'),
      shuiDian: calculateSummary('shuiDian'),
      waGong: calculateSummary('waGong'),
      muGong: calculateSummary('muGong'),
      youGong: calculateSummary('youGong'),
      anZhuang: calculateSummary('anZhuang'),
      wanGong: calculateSummary('wanGong'),
      daikaigong: calculateSummary('daikaigong'),
      shigongzhong: calculateSummary('shigongzhong'),
      jungong: calculateSummary('jungong'),
      tinggong: calculateSummary('tinggong'),
      tuidan: calculateSummary('tuidan'),
    },
  ];
});
</script>

<style lang="less" scoped>
:deep(.fw-b) {
  font-weight: bold;
}
</style>
